import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/utils/theme_util.dart';

/// 单选框
class SimpleAppRadio extends StatelessWidget {
  const SimpleAppRadio({
    Key? key,
    this.value = false,
    this.size = 18,
  }) : super(key: key);

  final bool value;

  final double size;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: size,
      height: size,
      padding: const EdgeInsets.all(1),
      child: AnimatedScale(
        scale: value ? 1 : 0,
        duration: const Duration(milliseconds: 200),
        curve: Curves.ease,
        child: Container(
            decoration: BoxDecoration(
          color: theme(context),
          shape: BoxShape.circle,
        )),
      ),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(
          width: 1,
          color: theme(context),
        ),
      ),
    );
  }
}

/// 单选框
class AppRadio extends StatefulWidget {
  const AppRadio({
    Key? key,
    this.value,
    this.onChanged,
    this.size = 18,
  }) : super(key: key);

  final bool? value;

  final Function(bool)? onChanged;

  final double size;

  @override
  State<AppRadio> createState() => _AppRadioState();
}

class _AppRadioState extends State<AppRadio> with SafeState<AppRadio> {
  bool _value = false;

  @override
  void initState() {
    super.initState();
    if (widget.value != null) _value = widget.value!;
  }

  @override
  void didUpdateWidget(covariant AppRadio oldWidget) {
    if (widget.value != _value && widget.value != null) {
      safeSetState(() => _value = widget.value!);
    }
    super.didUpdateWidget(oldWidget);
  }

  bool get _enable => widget.onChanged != null || widget.value != null;

  void _onTap() {
    safeSetState(() => _value = !_value);
    widget.onChanged?.call(_value);
  }

  @override
  Widget build(BuildContext context) {
    Widget box = Container(
      width: widget.size,
      height: widget.size,
      padding: const EdgeInsets.all(1),
      child: AnimatedScale(
        scale: _value ? 1 : 0,
        duration: const Duration(milliseconds: 100),
        child: Container(
            decoration: BoxDecoration(
          color: theme(context),
          shape: BoxShape.circle,
        )),
      ),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(
          width: 1,
          color: _enable ? theme(context) : disable(context),
        ),
      ),
    );

    if (widget.onChanged != null) {
      box = GestureDetector(
        onTap: _onTap,
        child: box,
      );
    }
    return box;
  }
}
